<template>
    <div>
        <div v-if="by==='day'">
            <button class="calendar-button text-xl" type="button" @click="open">{{ info.Period }}</button>
            <uni-calendar ref="calendar" class="uni-calendar--hook" :clear-date="true" :date="info.date" :insert="info.insert" :startDate="info.startDate"
                          :endDate="info.endDate" :range="info.range" @confirm="confirm" @close="close"/>
        </div>
        <div v-else>
          <picker indicator-s="text-xxl" mode="date" fields="month" :start="info.startDate" :end="info.endDate" :value="info.date" @change="confirm">
            <button class="calendar-button text-xl" type="button">{{ info.date }}</button>
          </picker>
        </div>

        <div class="cu-card margin-top">
            <text class='cuIcon-titles text-green'></text> <text class="text-xl" style="color: #777777">交易概况</text>
              <div class="cu-item padding-bottom-lg">
                  <div class="flex text-center margin-top margin-bottom">
                      <div class="flex-sub">
                          <div class="text-lg margin-bottom-sm" style="color: #9b9b9b">交易额</div>
                          <div class="solid-right text-price" style="color: #7a7a7a">{{businessIncome.salesVolume}}</div>
                      </div>
                      <div class="flex-sub">
                          <div class="text-lg margin-bottom-sm" style="color: #9b9b9b">交易笔数</div>
                          <div class="solid-right" style="color: #7a7a7a">{{businessIncome.transactionsNum}}</div>
                      </div>
                      <div class="flex-sub">
                          <div class="text-lg margin-bottom-sm" style="color: #9b9b9b">交易人数</div>
                          <div class="solid-right" style="color: #7a7a7a">{{customerNewAndOld.newNum+customerNewAndOld.oldNum}}</div>
                      </div>
                  </div>
              </div>

            <text class='cuIcon-titles text-green'></text> <text class="text-xl" style="color: #777777">交易时段分布</text>
            <div class="cu-item padding-bottom">
                <div class="bg-white nav">
                    <div class="flex text-center">
                        <div :class="'cu-item text-lg flex-sub '+(index===tradingPeriodTabCur?'text-green cur':'')" v-for="index in tradingPeriod" :key="index" @tap="tradingPeriodTabSelect" :data-id="index">
                            <text style="'color: #9f9f9f;'+(index===tradingPeriodTabCur?'text-green':'')">{{index}}</text>
                        </div>
                    </div>
                </div>
                <div class="ucharts_box_cont" style="height: 200px">
                    <canvas canvas-id="tradingPeriodCanvas" id="tradingPeriodCanvas" class="ucharts" @tap="canvasTap" />
                </div>
            </div>

            <text class='cuIcon-titles text-green'></text> <text class="text-xl" style="color: #777777">顾客总览</text>
            <div class="cu-item padding-bottom">
                <div class="ucharts_box_cont" style="height: 200px">
                    <canvas canvas-id="customerNewAndOldCanvas" id="customerNewAndOldCanvas" class="ucharts" @tap="canvasTap" />
                </div>
            </div>


          <text class='cuIcon-titles text-green'></text> <text class="text-xl" style="color: #777777">支付对账</text>
          <div class="cu-item padding-bottom">
            <div class="ucharts_box_cont" style="height: 200px">
              <canvas canvas-id="incomeReconcileCanvas" id="incomeReconcileCanvas" class="ucharts" @tap="canvasTap" />
            </div>

            <div class="flex text-center text-lg padding">
              <div class="flex-sub">
                <div style="color: #858585">实际收入</div>
                <div>{{businessIncomeReconcile.total}}</div>
              </div>
              <div v-if="businessIncomeReconcile.total!==0" class="flex-sub text-xxl"  style="color: #858585">
                =
              </div>
              <div v-if="businessIncomeReconcile.total!==0" class="flex-sub">
                <div style="color: #858585">总收入</div>
                <div>{{realIncome.toFixed(2)}}</div>
              </div>
              <div v-if="isAttach" class="flex-sub text-xxl" style="color: #858585">
                -
              </div>
              <div v-if="isAttach" class="flex-sub">
                <div style="color: #858585">优惠成本</div>
                <div>{{businessIncomeReconcile.salesVolumeByPayment['优惠活动']}}</div>
              </div>
            </div>
          </div>

          <div class="text-lg padding" style="text-align: center;color: #999999">
            <text>更详细请使用电脑访问rsms.golxen.com</text>
          </div>
        </div>
    </div>

</template>

<script>
import dateTimeUtils from "../../utils/dateTimeUtils";
import request from "../../utils/request";
import uCharts from "@qiun/ucharts";


let _self;
let canvaArcbar=[];

export default {
  name: "Report",
  data(){
    return{
      by:"",
      businessDate:{storeId: uni.getStorageSync("currentStoreMain").storeId},
      businessIncome:{},
        customerNewAndOld:{},
        businessIncomeReconcile:{},
      realIncome:0,
      isAttach:false,

        tradingPeriod: ["交易额","交易笔数"],
        tradingPeriodTabCur:"交易额",
        //折线图
        cWidth5: '',
        cHeight5: '',
        categoriesData:[],
        areaData:[],
        pixelRatio:1,


        //日历
      info: {
        range: true,
        insert: false,
      }
    }
  },

  onLoad:function (option) {
    if (option.by==="day"){
      uni.setNavigationBarTitle({
        title: '交易日报'
      })
        this.by=option.by
      this.info.endDate=dateTimeUtils.myGetDate(new Date(),-1).fullDate
      this.info.startDate=dateTimeUtils.myGetDate(new Date(),-90).fullDate
      this.info.date=dateTimeUtils.myGetDate(new Date(),-1).fullDate
      this.info.Period=this.info.date

        this.businessDate.startDate=this.info.date+"T00:00:00"
        this.businessDate.endDate=dateTimeUtils.myGetDate(new Date()).fullDate+"T00:00:00"
        request.post("/business/get/businessIncomeByHour",this.businessDate).then(res=>{
            this.businessIncome=res.data
            let row=Object.keys(this.businessIncome.incomeDetailBySalesVolume)
          let col=[]
          row.sort(function (a, b) {
            return a.localeCompare(b)
          })

          for (let i in row){
            col.push(this.businessIncome.incomeDetailBySalesVolume[row[i]])
          }
          this.categoriesData=row
          this.areaData=col

          _self = this;
          //实现自动获取宽高并赋值
          _self.$nextTick(() => {
            let info = uni.createSelectorQuery().in(_self).select('.ucharts_box_cont');
            info.boundingClientRect(function(data) {
              // 获取元素的各种参数
              _self.cWidth5=data.width;
              _self.cHeight5=data.height;
              _self.fillDataArea(_self.categoriesData,_self.areaData,"tradingPeriodCanvas");
            }).exec();
          })

        })
        request.post("/business/get/businessIncomeReconcileByPayment",this.businessDate).then(res=>{
            this.businessIncomeReconcile=res.data
          let columnStack= {
            categories: [""],
                series: []
          }
          for (let payment in this.businessIncomeReconcile.salesVolumeByPayment){
            if (payment==="优惠活动")
              continue
            columnStack.series.push({
              name:payment,
              data:[this.businessIncomeReconcile.salesVolumeByPayment[payment]]
            })
          }

          _self = this;
          //实现自动获取宽高并赋值
          _self.$nextTick(() => {
            let info = uni.createSelectorQuery().in(_self).select('.ucharts_box_cont');
            info.boundingClientRect(function(data) {
              // 获取元素的各种参数
              _self.cWidth5=data.width;
              _self.cHeight5=data.height;
              _self.fillDataColumn(columnStack,"incomeReconcileCanvas");
            }).exec();
          })
          if(this.businessIncomeReconcile.salesVolumeByPayment["优惠活动"]!==undefined){
            this.realIncome= this.businessIncomeReconcile.total+this.businessIncomeReconcile.salesVolumeByPayment["优惠活动"]
            this.isAttach=true
          }else{
            this.realIncome=this.businessIncomeReconcile.total
            this.isAttach=false
          }

        })
        request.post("/customer/get/customerNewAndOld",this.businessDate).then(res=>{
            this.customerNewAndOld=res.data

            let ringData=[
                {
                    name:"新顾客",
                    data:this.customerNewAndOld.newNum
                },
                {
                    name:"老顾客",
                    data:this.customerNewAndOld.oldNum
                }
            ]
            _self = this;
            //实现自动获取宽高并赋值
            _self.$nextTick(() => {
                let info = uni.createSelectorQuery().in(_self).select('.ucharts_box_cont');
                info.boundingClientRect(function(data) {
                    // 获取元素的各种参数
                    _self.cWidth5=data.width;
                    _self.cHeight5=data.height;
                    _self.fillDataRing(ringData,"customerNewAndOldCanvas");
                }).exec();
            })

        })

    } else{
      uni.setNavigationBarTitle({
        title: '交易月报'
      })
      this.by=option.by
      let nowDate=new Date()
      let endDate = nowDate.setMonth((nowDate.getMonth() - 1));
      let startDate=nowDate.setFullYear((nowDate.getFullYear()-1))
      endDate=new Date(endDate)
      startDate=new Date(startDate)
      let m
      if (endDate.getMonth()+1<10){
        m="0"+(endDate.getMonth()+1)
      }else
        m=endDate.getMonth()+1
      this.info.endDate=endDate.getFullYear()+"-"+m
      this.info.startDate=startDate.getFullYear()+"-"+m
      this.info.date=this.info.endDate

      this.businessDate.startDate=this.info.date+"-01T00:00:00"
      nowDate=new Date()
      if (nowDate.getMonth()+1<10){
        m="0"+(nowDate.getMonth()+1)
      }else
        m=nowDate.getMonth()+1

      this.businessDate.endDate=nowDate.getFullYear()+"-"+m+"-01T00:00:00"
      request.post("/business/get/businessIncomeByHour",this.businessDate).then(res=>{
        this.businessIncome=res.data
        let row=Object.keys(this.businessIncome.incomeDetailBySalesVolume)
        let col=[]
        row.sort(function (a, b) {
          return a.localeCompare(b)
        })

        for (let i in row){
          col.push(this.businessIncome.incomeDetailBySalesVolume[row[i]])
        }
        this.categoriesData=row
        this.areaData=col

        _self = this;
        //实现自动获取宽高并赋值
        _self.$nextTick(() => {
          let info = uni.createSelectorQuery().in(_self).select('.ucharts_box_cont');
          info.boundingClientRect(function(data) {
            // 获取元素的各种参数
            _self.cWidth5=data.width;
            _self.cHeight5=data.height;
            _self.fillDataArea(_self.categoriesData,_self.areaData,"tradingPeriodCanvas");
          }).exec();
        })

      })
      request.post("/business/get/businessIncomeReconcileByPayment",this.businessDate).then(res=>{
        this.businessIncomeReconcile=res.data
        let columnStack= {
          categories: [""],
          series: []
        }
        for (let payment in this.businessIncomeReconcile.salesVolumeByPayment){
          if (payment==="优惠活动")
            continue
          columnStack.series.push({
            name:payment,
            data:[this.businessIncomeReconcile.salesVolumeByPayment[payment]]
          })
        }

        _self = this;
        //实现自动获取宽高并赋值
        _self.$nextTick(() => {
          let info = uni.createSelectorQuery().in(_self).select('.ucharts_box_cont');
          info.boundingClientRect(function(data) {
            // 获取元素的各种参数
            _self.cWidth5=data.width;
            _self.cHeight5=data.height;
            _self.fillDataColumn(columnStack,"incomeReconcileCanvas");
          }).exec();
        })
        if(this.businessIncomeReconcile.salesVolumeByPayment["优惠活动"]!==undefined){
          this.realIncome= this.businessIncomeReconcile.total+this.businessIncomeReconcile.salesVolumeByPayment["优惠活动"]
          this.isAttach=true
        }else{
          this.realIncome=this.businessIncomeReconcile.total
          this.isAttach=false
        }

      })
      request.post("/customer/get/customerNewAndOld",this.businessDate).then(res=>{
        this.customerNewAndOld=res.data

        let ringData=[
          {
            name:"新顾客",
            data:this.customerNewAndOld.newNum
          },
          {
            name:"老顾客",
            data:this.customerNewAndOld.oldNum
          }
        ]
        _self = this;
        //实现自动获取宽高并赋值
        _self.$nextTick(() => {
          let info = uni.createSelectorQuery().in(_self).select('.ucharts_box_cont');
          info.boundingClientRect(function(data) {
            // 获取元素的各种参数
            _self.cWidth5=data.width;
            _self.cHeight5=data.height;
            _self.fillDataRing(ringData,"customerNewAndOldCanvas");
          }).exec();
        })

      })
    }






  },

  methods: {
    open() {
      this.$refs.calendar.open()
    },
    close(){
      console.log('弹窗关闭');
    },
    confirm(e) {
      console.log(e,this.by)
        if (this.by==="day"&&e.range.before!==""){
            if (e.range.before===e.range.after||e.range.after==="")
                this.info.Period=e.range.before
            else
                this.info.Period=e.range.before+" -> "+e.range.after
            this.businessDate.startDate=e.range.before+"T00:00:00"
            if (e.range.after==="")
              e.range.after=e.range.before
            let endDate=new Date(e.range.after)
            endDate=dateTimeUtils.dateTimePlusMinus(endDate,1)
            endDate=dateTimeUtils.dateTimeFormat(endDate)
            this.businessDate.endDate=endDate
        }else {
          this.businessDate.startDate=e.detail.value+"-01T00:00:00"
          let startDate=new Date(e.detail.value+"-01T00:00:00")
          let endDate=new Date(startDate.setMonth(startDate.getMonth()+1))
          let m
          if (endDate.getMonth()+1<10){
            m="0"+(endDate.getMonth()+1)
          }else
            m=endDate.getMonth()+1
          this.businessDate.endDate=endDate.getFullYear()+"-"+m+"-01T00:00:00"
          console.log(this.businessDate.startDate,this.businessDate.endDate)
        }
          request.post("/business/get/businessIncomeByHour",this.businessDate).then(res=>{
            this.businessIncome=res.data
            let row=Object.keys(this.businessIncome.incomeDetailBySalesVolume)
            let col=[]
            row.sort(function (a, b) {
              return a.localeCompare(b)
            })
            for (let i in row){
              col.push(this.businessIncome.incomeDetailBySalesVolume[row[i]])
            }
            this.categoriesData=row
            this.areaData=col
            this.updateChartsArea("tradingPeriodCanvas")

          })
          request.post("/business/get/businessIncomeReconcileByPayment",this.businessDate).then(res=>{
            this.businessIncomeReconcile=res.data
            let columnStack= {
              categories: [""],
              series: []
            }
            for (let payment in this.businessIncomeReconcile.salesVolumeByPayment){
              if (payment==="优惠活动")
                continue
              columnStack.series.push({
                name:payment,
                data:[this.businessIncomeReconcile.salesVolumeByPayment[payment]]
              })
            }
            if(this.businessIncomeReconcile.salesVolumeByPayment["优惠活动"]!==undefined){
              this.realIncome= this.businessIncomeReconcile.total+this.businessIncomeReconcile.salesVolumeByPayment["优惠活动"]
              this.isAttach=true
            }else{
              this.realIncome=this.businessIncomeReconcile.total
              this.isAttach=false
            }

            this.updateChartsColumn("incomeReconcileCanvas",columnStack)
          })
          request.post("/customer/get/customerNewAndOld",this.businessDate).then(res=>{
            this.customerNewAndOld=res.data

            let ringData=[
              {
                name:"新顾客",
                data:this.customerNewAndOld.newNum
              },
              {
                name:"老顾客",
                data:this.customerNewAndOld.oldNum
              }
            ]
            this.updateChartsRing("customerNewAndOldCanvas",ringData)
          })


    },
      fillDataArea(categoriesData,areaData,canvasId) {
          let _this = this;
          let Area = {
              categories: [],
              series: []
          };
          Area.categories=categoriesData,
              Area.series=[
                  {
                      color:"#5ae93a",
                      data:areaData,
                      name: "",
                      pointShape: "circle",
                      show: true,
                      type: "line",
                  }
              ]
          _this.showArea(canvasId, Area);
      },
      fillDataRing(ringData,canvasId) {
          let _this = this;
          let Ring = {
              series: []
          };
          Ring.series=ringData
          _this.showRing(canvasId, Ring);
      },
    fillDataColumn(columnData,canvasId) {
      let _this = this;
      let Column = {
        series: []
      };
      Column.series=columnData.series
      Column.categories=columnData.categories
      _this.showColumn(canvasId, Column);
    },
      showArea(canvasId, chartData) {
          canvaArcbar[canvasId] = new uCharts({
              context:uni.createCanvasContext(canvasId, this),
              type: 'area',
              padding:[10,20,5,5],
              legend:{
                  show:false,
              },
              dataLabel:false,
              dataPointShape:false,
              // background:'#FFFFFF',
              pixelRatio:_self.pixelRatio,
              categories: chartData.categories,
              series: chartData.series,
              animation: true,
              xAxis: {
                  type:'grid',
                  gridColor:'rgba(255,255,255,0)',
                  gridType:'dash',
                  dashLength:8,
                  boundaryGap:'justify',//两端不留白配置
                labelCount: 5, //默认显示个数
                itemCount:chartData.length,
                  fontSize:10,
              },
              yAxis: {
                  // gridType:'solid',
                  disableGrid:true,
                  gridColor:'rgba(255,255,255,.2)',
                  // dashLength:4,
                  splitNumber:this.setSplitNumber(this.areaData),
                  min:0,

                  // showTitle:true,
                  data:[{
                      tofix:0,
                      fontSize:10,
                      // title:"金额"
                  }]
                  // format:(val)=>{return val.toFixed(2)},
              },
              width: _self.cWidth5*_self.pixelRatio,
              height: _self.cHeight5*_self.pixelRatio,
              extra: {
                  area:{
                      type: 'straight',
                      opacity:0,
                      addLine:true,
                      width:0
                  }
              }
          });
      },
      showRing(canvasId,chartData){
          canvaArcbar[canvasId]=new uCharts({
              context:uni.createCanvasContext(canvasId, this),
              type: 'ring',
              series: chartData.series,
              width: _self.cWidth5*_self.pixelRatio,
              height: _self.cHeight5*_self.pixelRatio,
            title: {
              name: "共"+(chartData.series[0].data+chartData.series[1].data)+"人",
              color: '#666666',
              fontSize: 12*_self.pixelRatio,
            },
              extra: {
                  ring: {
                      labelWidth:15
                  }
              },
          });
      },
    showColumn(canvasId,chartData){
      canvaArcbar[canvasId]=new uCharts({
        context:uni.createCanvasContext(canvasId, this),
        type: 'bar',
        padding:[10,30,10,10],
        series: chartData.series,
        categories: chartData.categories,
        width: _self.cWidth5*_self.pixelRatio,
        height: _self.cHeight5*_self.pixelRatio,

        legend: {
          position:"bottom",
          float:"left",
        },
        xAxis: {
          boundaryGap: "justify",
          disableGrid: false,
          axisLine: false,
          min: 0,
          fontSize:10,
        },
        yAxis: {
          fontSize:10,
        },
        extra: {
          bar: {
            type: "group",
            width: 30,
            meterBorde: 1,
            meterFillColor: "#FFFFFF",
            activeBgColor: "#000000",
            activeBgOpacity: 0.08,
            linearType: "custom",
            barBorderCircle: true,
            seriesGap: 2,
            categoryGap: 2
          }
        }

      });
    },
      setSplitNumber(arr){
          let splitNumber = 5;
          if(arr.length!==0){
              let max = Math.max.apply(null,arr);
              let min = Math.min.apply(null,arr);
              if((Number(max) - Number(min) >=5) || (Number(max) - Number(min) === 0)){
                  splitNumber =  5;
              }else {
                  splitNumber = Number(max) - Number(min);
              }

          }
          if (splitNumber<1)
              splitNumber=1
          return splitNumber
      },
    updateChartsArea(id) {
          canvaArcbar[id].updateData({
              categories: this.categoriesData,
              series:[
                  {
                      color:"#5ae93a",
                      data:this.areaData,
                      name: "",
                      pointShape: "circle",
                      show: true,
                      type: "line",
                  }
              ]
          })
      },
    updateChartsRing(id,ringData) {
      canvaArcbar[id].updateData({
        series:ringData,
        title:{
          name: "共"+(ringData[0].data+ringData[1].data)+"人"
        }
      })
    },
    updateChartsColumn(id,barData) {
      canvaArcbar[id].updateData({
        series:barData.series,
        categories:barData.categories
      })
    },
      canvasTap(e){
       canvaArcbar[e.target.id].showToolTip(e, {
         formatter: (item, category, index, opts) => {
           console.log(item, category, index, opts)
             if (category!==undefined)
                return category + " : " + item.data;
             else
                 return item.name + " : " + item.data;
         }
       });
      },
      tradingPeriodTabSelect(e) {
          if (this.tradingPeriodTabCur!==e.currentTarget.dataset.id){
              this.tradingPeriodTabCur= e.currentTarget.dataset.id
              if (this.tradingPeriodTabCur==="交易笔数"){
                  let row=Object.keys(this.businessIncome.incomeDetailByTransactionsNum)
                  let col=[]
                  row.sort(function (a, b) {
                      return a.localeCompare(b)
                  })

                  for (let i in row){
                      col.push(this.businessIncome.incomeDetailByTransactionsNum[row[i]])
                  }
                  this.categoriesData=row
                  this.areaData=col
                canvaArcbar["tradingPeriodCanvas"].updateData({
                  yAxis: {
                    disableGrid:true,
                    gridColor:'rgba(255,255,255,.2)',
                    splitNumber:this.setSplitNumber(this.areaData),
                    min:0,

                    data:[{
                      tofix:0,
                      fontSize:10,
                    }]
                  }
                })
              }else {
                  let row=Object.keys(this.businessIncome.incomeDetailBySalesVolume)
                  let col=[]
                  row.sort(function (a, b) {
                      return a.localeCompare(b)
                  })

                  for (let i in row){
                      col.push(this.businessIncome.incomeDetailBySalesVolume[row[i]])
                  }
                  this.categoriesData=row
                  this.areaData=col
                canvaArcbar["tradingPeriodCanvas"].updateData({
                  yAxis: {
                    disableGrid:true,
                    gridColor:'rgba(255,255,255,.2)',
                    splitNumber:this.setSplitNumber(this.areaData),
                    min:0,

                    data:[{
                      tofix:2,
                      fontSize:10,
                    }]
                  }
                })
              }

              this.updateChartsArea("tradingPeriodCanvas")
          }
      },

  }
}
</script>

<style scoped>
.ucharts_box_cont{
    width: 100%;
}
.ucharts {
    height: 100%;
    width: 100%;
}
</style>